"""
FileName：persistent_auth_manager.py
Description：
Author：gaojiahui
Time：2025/8/14 16:49
Website：https://gitee.com/gao-jiahui
"""
import json

from auth_manager import AuthManager
from request_token import get_current_user
"""会话状态维持机制"""

class PersistentAuthManager(AuthManager):
    def __init__(self,base_url,cookie_file=".cookies"):
        super().__init__(base_url)
        self.cookie_file = cookie_file
        self.load_cookies()

    def login(self,username,password):
        """登录并保存Cookies"""
        success = super().login(username,password)
        if success:
            self.save_cookies()
        return success

    def save_cookies(self):
        """保存Cookies到文件"""
        with open(self.cookie_file,"w") as f:
            cookies = [
                {"name": c.name,"value": c.value,"domain": c.domain, "path": c.path}
                for c in self.session.cookies
            ]
            json.dump(cookies,f)

    def load_cookies(self):
        """从文件加载Cookies"""
        try:
            with open(self.cookie_file, 'r') as f:
                cookies = json.load(f)
                for cookie in cookies:
                    self.session.cookies.set(
                        cookie["name"],
                        cookie["value"],
                        domain=cookie["domain"],
                        path=cookie["path"]
                    )
            # 验证Cookies是否有效
            if self.validate_session():
                print("从cookies恢复会话成功")
                return True
        except FileNotFoundError:
            print("未找到Cookies文件")
        return False

    def validate_session(self):
        """验证会话是否有效"""
        url = f"{self.base_url}/admin/user/info"
        response = self.session.get(url)
        return response.status_code == 200

    def encrypt_cookie_file(file_path, key):
        """加密Cookie文件"""
        # 使用AES加密算法实现

    def decrypt_cookie_file(file_path, key):
        """解密Cookie文件"""

# 初始化认证管理器
auth_manager = PersistentAuthManager("http://pig-gateway:9999")

# 首次使用需要登录
if not auth_manager.validate_session():
    print("需要登录...")
    auth_manager.login("admin","YehdBPev")

# 后续使用自动恢复会话
print("当前用户:",get_current_user(auth_manager))